export class Praise {
  context: any = null; // 绘制cavas对象
  width = 0;
  height = 0;
  imgsList: any = []; // 绘制的图片列表
  renderList: any = []; // 渲染对象列表
  scaleTime = 0.2;// 百分比
  duration = 0;
  constructor () {
    this.loadImages();
    const canvas: any = document.getElementById('canvas');
    if (canvas) {
      this.context = canvas.getContext('2d');
      this.width = canvas.width;
      this.height = canvas.height;
    }
  }

  /**
   * 加载图片
   */
  loadImages () {
    const images = [
      'https://h5static4.ihumand.com/baidu-miniprogram/test/1.png',
      'https://h5static4.ihumand.com/baidu-miniprogram/test/2.png',
      'https://h5static4.ihumand.com/baidu-miniprogram/test/3.png'
    ];
    const arr = [] as Array<Promise<any>>;
    images.forEach((item) => {
      const p = new Promise((resolve) => {
        const img = new Image();
        img.onerror = img.onload = resolve.bind(null, img);
        img.src = item;
      });
      arr.push(p);
    });
    Promise.all(arr).then((imgsList) => {
      this.imgsList = imgsList.filter((d) => {
        if (d && d.width > 0) return true;
        return false;
      });
    });
  }

  /**
   * 获取当前图片的尺寸大小
   */
  getScale (runingTime: any) {
    const basicScale = 1;
    if (runingTime < this.scaleTime) {
      /** 在scaleTime时间范围内 图片尺寸变化到正常大小 */
      return +((runingTime / this.scaleTime).toFixed(2)) * basicScale;
    } else if (runingTime > 0.6) {
      /** 指定动画运行时间大于60%时，尺寸逐渐缩小 */
      return (1 + 0.6 - runingTime).toFixed(2);
    } else {
      return basicScale;
    }
  }

  /**
   * 获取随机数
   * @param min 随机数最小值
   * @param max 随机数最大值
   */
  getRandom (min: number, max: number) {
    return min + Math.floor(Math.random() * (max - min + 1));
  }

  /**
   * 获取垂直方向偏移值
   * @param image
   * @param runingTime
   * @returns
   */
  getTranslateY (image: any, runingTime: any) {
    return this.height * (1 - runingTime);
  }

  /**
   * 获取水平方向偏移值
   * @param runingTime
   * @returns
   */
  getTranslateX (basicX: number, angle: number, ratio: number, runingTime: any) {
    if (runingTime < this.scaleTime) { // 放大期间，不进行摇摆位移
      return basicX;
    } else {
      return basicX + ratio * Math.sin(angle * (runingTime - this.scaleTime));
    }
  }

  /**
   * 处理渐隐效果
   * @param runingTime
   * @returns
   */
  getAlpha (runingTime: number) {
    /** 定义动画运行至70%开始渐隐 */
    const basic = 0.7;
    if (basic > runingTime) {
      return 1;
    } else {
      return 1 - +((runingTime - basic) * 3).toFixed(2);
    }
  }

  /**
   * 创建渲染对象
   */
  createRender () {
    if (this.imgsList.length === 0) return null;
    // const basicScale = [0.6, 0.9, 1.2][getRandom(0, 2)];
    // 随机读取一个图片来渲染
    const image = this.imgsList[this.getRandom(0, this.imgsList.length - 1)];
    const offset = 20;
    const basicX = this.width / 2 + this.getRandom(-offset, offset);
    const angle = this.getRandom(2, 10);
    const ratio = this.getRandom(50, 80) * ((this.getRandom(0, 1) ? 1 : -1));
    // const basicAlpha = this.getRandom(6, 8) / 10;
    return (runingTime: number) => {
      /** runingTime为1表示动画运行结束 */
      if (runingTime >= 1) return true;
      if (this.context) {
        this.context.save();
        const scale = this.getScale(runingTime);
        const translateX = this.getTranslateX(basicX, angle, ratio, runingTime);
        const translateY = this.getTranslateY(image, runingTime);
        this.context.translate(translateX, translateY);
        this.context.scale(scale, scale);
        this.context.globalAlpha = this.getAlpha(runingTime);
        this.context.drawImage(
          image,
          -100,
          -100,
          400,
          400
        );
        this.context.restore();
      }
    };
  }

  /**
   * 重复执行动画并删除掉已经运行完成的动画
   */
  scan () {
    this.context.clearRect(0, 0, this.width, this.height);
    this.context.fillStyle = 'rgba(0,0,0,0)';
    this.context.fillRect(0, 0, this.width, this.height);
    let index = 0;
    let length = this.renderList.length;
    if (length > 0) {
      this.requestFrame(this.scan.bind(this));
      // this.scanning = true;
    } else {
      // this.scanning = false;
    }
    while (index < length) {
      const child = this.renderList[index];
      /** 计算当前动画运行时间进度 */
      const runingTime = (Date.now() - child.timestamp) / child.duration;
      if (!child || !child.render || child.render(runingTime)) {
        // 结束了，删除该动画
        this.renderList.splice(index, 1);
        length--;
      } else {
        // continue
        index++;
      }
    }
  }

  /**
   * 开启渲染对象
   * @returns
   */
  start () {
    const render = this.createRender();
    // const duration = getRandom(1500, 3000);
    this.duration = 2000;
    this.renderList.push({
      render,
      duration: this.duration,
      timestamp: Date.now()
    });
    this.scan();
  }

  /**
   * 执行动画，每秒60次
   * @param callback 回调函数
   */
  requestFrame (callback: any) {
    window.requestAnimationFrame && window.requestAnimationFrame(callback);
  }
}
